//
//  LiveViewController.m
//  斗鸡TV
//
//  Created by admin on 2017/2/10.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "LiveViewController.h"
#import "ApplicitonClass.h"
#define More_Url @"http://live.9158.com/Fans/GetHotLive"
#import "LiveCollectionViewCell.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface LiveViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    
    UIButton * dismissBtn;
    UIButton * MyliveBtn;
    NSString * urlS;
    UICollectionView * collectView;
    UILabel * nameL;
    HomeModel * homeM;
}
@property (weak, nonatomic) UIView *PlayerView;
@property (nonatomic, strong) IJKFFMoviePlayerController * ijPlayer;
@end

@implementation LiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initPlayer];
    
    UICollectionViewFlowLayout * layout = [UICollectionViewFlowLayout new];
    layout.itemSize = CGSizeMake(70, 70);
    layout.minimumInteritemSpacing = 1;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    collectView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, HEIGHT-70, WIDTH, 70) collectionViewLayout:layout];
    collectView.backgroundColor = [UIColor clearColor];
    collectView.dataSource = self;
    collectView.delegate = self;
    
    [collectView registerClass:[LiveCollectionViewCell class] forCellWithReuseIdentifier:@"lcell"];
    [self.view addSubview:collectView];

    
    dismissBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-50, 20, 50, 50)];
    [dismissBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [dismissBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [dismissBtn addTarget:self action:@selector(dismissVc) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:dismissBtn];
    
    MyliveBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 20, 100, 50)];
    [MyliveBtn setTitle:@"切换直播" forState:UIControlStateNormal];
    [MyliveBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [MyliveBtn addTarget:self action:@selector(Mylive) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:MyliveBtn];
    
    nameL = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, WIDTH-50, 50)];
    nameL.numberOfLines = 0;
    nameL.textColor = [UIColor orangeColor];
    nameL.text = [NSString stringWithFormat:@"%@\n%@",self.sHM.myname,self.sHM.signatures];
    [self.view addSubview:nameL];
    [self loadData];
    
  
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return  homeM.list.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"lcell";
    LiveCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
  
    SubHomeModel * hm = homeM.list[indexPath.row];
    NSLog(@"%ld",(long)indexPath.row);
    [cell setCellData:hm];
    
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SubHomeModel * hm = homeM.list[indexPath.row];
    self.sHM = hm;
      [self initPlayer];
}
-(void)loadData
{
    //数据请求（Block回调方法）
    [self httpPostUrl:More_Url params:nil successBlock:^(NSDictionary *dict) {
        
        if ([dict[@"code"] intValue] == 100)
        {
            NSDictionary * data = [dict dictionaryForKey:@"data"];
            homeM = [[HomeModel alloc]initWithDictionary:data error:nil];
            
        }
        
        [collectView reloadData];
    } errorBlock:^(NSError *error) {
        
        
    }];
}

-(void)initPlayer
{
    

    [self showLoading];
    if (_ijPlayer) {
        
        [_ijPlayer shutdown];
        [_ijPlayer.view removeFromSuperview];
        _ijPlayer = nil;
    }

        urlS = @"rtmp://localhost:1935/rtmplive/room";

        if (self.sHM.flv && self.sHM.flv.length > 0) {
            urlS = self.sHM.flv;
        }
    
    NSLog(@"%@",urlS);
    nameL.text = [NSString stringWithFormat:@"%@\n%@",self.sHM.myname,self.sHM.signatures];
    _ijPlayer = [[IJKFFMoviePlayerController alloc]initWithContentURL:[NSURL URLWithString:urlS] withOptions:nil];
    
    UIView *playerView = [_ijPlayer view];
    
    /**
     *   播放的界面
     */
    UIView *displayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    self.PlayerView = displayView;
    self.PlayerView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.PlayerView];
    
    playerView.frame = self.PlayerView.bounds;
    playerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    [self.PlayerView insertSubview:playerView atIndex:1];
    [_ijPlayer setScalingMode:IJKMPMovieScalingModeAspectFill];
    
    [_ijPlayer prepareToPlay];
    
    [self.view bringSubviewToFront:dismissBtn];
    [self.view bringSubviewToFront:MyliveBtn];
    [self.view bringSubviewToFront:collectView];
    [self.view bringSubviewToFront:nameL];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stateDidChange) name:IJKMPMoviePlayerLoadStateDidChangeNotification object:_ijPlayer];
}

-(void)Mylive
{
    [self initPlayer];
}

-(void)stateDidChange
{

     if ((_ijPlayer.loadState & IJKMPMovieLoadStatePlaythroughOK) != 0)
     {
         NSLog(@"加载成功");
         [self dismissLoading];
     }
    
}



-(void)dismissVc
{
     [self dismissLoading];
    // 关闭视屏
    [_ijPlayer stop];
    [_ijPlayer shutdown];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
